# Author: zhaozeliang
# Date: 2025-09-06

from rest_framework import generics, filters, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q, Max, Min, Avg
from django.db import models
from .models import ProductCategory, Product, ProductPrice, ProductPerformance
from .serializers import (
    ProductCategorySerializer,
    ProductSerializer,
    ProductListSerializer,
    ProductDetailSerializer,
    ProductPriceSerializer,
    ProductPerformanceSerializer
)

class ProductCategoryListView(generics.ListCreateAPIView):
    """产品分类列表视图"""
    queryset = ProductCategory.objects.all()
    serializer_class = ProductCategorySerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

class ProductListView(generics.ListAPIView):
    """产品列表视图"""
    queryset = Product.objects.filter(status='active')
    serializer_class = ProductListSerializer
    permission_classes = [permissions.AllowAny]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['category', 'risk_level', 'status']
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['created_at', 'name']
    ordering = ['-created_at']

class ProductDetailView(generics.RetrieveAPIView):
    """产品详情视图"""
    queryset = Product.objects.all()
    serializer_class = ProductDetailSerializer
    permission_classes = [permissions.AllowAny]

@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def product_search(request):
    """产品搜索"""
    query = request.GET.get('q', '')
    category = request.GET.get('category', '')
    risk_level = request.GET.get('risk_level', '')
    
    products = Product.objects.filter(status='active')
    
    if query:
        products = products.filter(
            Q(name__icontains=query) | 
            Q(code__icontains=query) | 
            Q(description__icontains=query)
        )
    
    if category:
        products = products.filter(category_id=category)
    
    if risk_level:
        products = products.filter(risk_level=risk_level)
    
    serializer = ProductListSerializer(products, many=True)
    return Response(serializer.data)

@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def product_recommendations(request):
    """产品推荐"""
    user = request.user
    
    # 基础推荐逻辑
    recommended_products = Product.objects.filter(status='active')
    
    # 如果用户已登录，根据用户风险等级推荐
    if user.is_authenticated and user.risk_level:
        recommended_products = recommended_products.filter(risk_level=user.risk_level)
    
    # 限制返回数量
    recommended_products = recommended_products[:10]
    
    serializer = ProductListSerializer(recommended_products, many=True)
    return Response({
        'message': '产品推荐',
        'products': serializer.data
    })

class ProductPriceListView(generics.ListAPIView):
    """产品价格历史视图"""
    serializer_class = ProductPriceSerializer
    permission_classes = [permissions.AllowAny]
    
    def get_queryset(self):
        product_id = self.kwargs['product_id']
        return ProductPrice.objects.filter(product_id=product_id).order_by('-price_date')

class ProductPerformanceListView(generics.ListAPIView):
    """产品业绩历史视图"""
    serializer_class = ProductPerformanceSerializer
    permission_classes = [permissions.AllowAny]
    
    def get_queryset(self):
        product_id = self.kwargs['product_id']
        return ProductPerformance.objects.filter(product_id=product_id).order_by('-performance_date')

@api_view(['GET'])
@permission_classes([permissions.AllowAny])
def product_stats(request, product_id):
    """产品统计信息"""
    try:
        product = Product.objects.get(id=product_id)
    except Product.DoesNotExist:
        return Response({'error': '产品不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    # 获取最新价格
    latest_price = ProductPrice.objects.filter(product=product).order_by('-price_date').first()
    
    # 获取最新业绩
    latest_performance = ProductPerformance.objects.filter(product=product).order_by('-performance_date').first()
    
    # 计算价格统计
    price_stats = ProductPrice.objects.filter(product=product).aggregate(
        max_price=Max('price'),
        min_price=Min('price'),
        avg_price=Avg('price')
    )
    
    return Response({
        'product_id': product.id,
        'product_name': product.name,
        'latest_price': latest_price.price if latest_price else None,
        'price_date': latest_price.price_date if latest_price else None,
        'daily_return': latest_performance.daily_return if latest_performance else None,
        'monthly_return': latest_performance.monthly_return if latest_performance else None,
        'yearly_return': latest_performance.yearly_return if latest_performance else None,
        'max_price': price_stats['max_price'],
        'min_price': price_stats['min_price'],
        'avg_price': price_stats['avg_price'],
        'risk_level': product.risk_level
    })
